<?php namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\User;
use App\UserInfo;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 获取永固列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserList(Request $request)
    {
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page     = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit    = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $keyword  = !is_null($request->get('keyword')) ? $request->get('keyword') : '';

        $pageInfo=[
            'page'=>$page,
            'limit'=>$limit
        ];

        $page   = $page - 1;

        $users  = User::whereRole(0);

        if($keyword != ''){
            $userIds = UserInfo::where('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id');

            $users->whereIn('id',$userIds)->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $pageInfo['total']  = $users->count();

        $users = $users->orderBy("created_at", "desc")->offset($page * $limit)->limit($limit)->get();

        if (count($users) > 0){
            foreach ($users as $user) {
                /** @var User $user */
                $user->userInfo;
                if($user->userInfo){
                    $user->userInfo->photo_url = FileManager::getImgUrl($user->userInfo->photo_id);
                }
            }
        }

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $users,'page_info'=>$pageInfo]);
    }
}